package com.blog.util;

import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.frs.v2.FrsClient;
import com.huaweicloud.sdk.frs.v2.model.FaceSearchBase64Req;
import com.huaweicloud.sdk.frs.v2.model.SearchFaceByBase64Request;
import com.huaweicloud.sdk.frs.v2.model.SearchFaceByBase64Response;
import com.huaweicloud.sdk.frs.v2.region.FrsRegion;

import java.io.IOException;

public class FaceUtils {
    public String searchFace(String imagePath) throws IOException {
        String faceBase64 = Base64Utils.imageToBase64(imagePath);
        // 获取密钥
        ICredential auth = new KeyUtils().getKey();

        FrsClient client = FrsClient.newBuilder()
                .withCredential(auth)
                .withRegion(FrsRegion.valueOf("cn-north-4"))
                .build();

        // 调用人脸搜索接口
        SearchFaceByBase64Request request = new SearchFaceByBase64Request();

        // 人脸库名
        request.withFaceSetName("blog_face_set");
        FaceSearchBase64Req body = new FaceSearchBase64Req();
        //相似度阈值
        body.withThreshold((double) 0.9);
        // 人脸图片
        body.withImageBase64(faceBase64);
        // 图片格式
        request.withBody(body);
        try {
            SearchFaceByBase64Response response = client.searchFaceByBase64(request);
            return response.getFaces().get(0).getExternalImageId();
        } catch (ConnectionException | RequestTimeoutException | ServiceResponseException e) {
            e.printStackTrace();
        }
        return null;
    }

}
